/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package mx.netbrain.bean;

import java.io.IOException;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import mx.netbrain.dao.UserDao;
import mx.netbrain.dao.impl.UserDaoImpl;
import mx.netbrain.model.User;
import org.primefaces.context.RequestContext;

/**
 *
 * @author Julian
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

    private User user;

    /**
     * Creates a new instance of LoginBean
     */
    public LoginBean() {
    }

    public void login(ActionEvent actionEvent) throws IOException {
        RequestContext context = RequestContext.getCurrentInstance();
        FacesMessage msg = null;
        boolean loggedIn = false;
        ExternalContext externalContent = FacesContext.getCurrentInstance().getExternalContext();
        UserDao userDao = new UserDaoImpl();
        user = userDao.findForUser(user);

        System.out.println("Este es el valor de USER: " + user);

        if (user != null) {
            loggedIn = true;
            msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Bienvenido", user.getName());
            FacesContext.getCurrentInstance().addMessage(null, msg);
            context.addCallbackParam("loggedIn", loggedIn);
            externalContent.getSessionMap().put("userSession", user);
            if (user.getType() == 1) {
                externalContent.redirect(externalContent.getRequestContextPath() + "/netbrain.jsf?faces-redirect=true&userId=" + user.getId());
            } else {
                externalContent.redirect(externalContent.getRequestContextPath() + "/netbrainUser.jsf?faces-redirect=true&userId=" + user.getId());
            }
            FacesContext session = FacesContext.getCurrentInstance();
            session.getExternalContext().getSessionMap().put("user", user);
        } else {
            loggedIn = false;
            msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Login Error", "Favor de validar sus datos");
            FacesContext.getCurrentInstance().addMessage(null, msg);
            context.addCallbackParam("loggedIn", loggedIn);
        }
    }

    public boolean isLoggedIn() {
        return user != null;
    }

    public User getUser() {
        if (user == null) {
            user = new User();
        }
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}
